package com.mysite.websocket.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.mysite.websocket.util.JsonUtil;
import com.mysite.websocket.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mysite.websocket.service.UserService;

@Controller
public class LoginController extends BaseController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = { "/", "/login", "/index" }, method = RequestMethod.GET)
	public String login(HttpSession session, ModelMap modelMap) {
        UserVo user = (UserVo) session.getAttribute("CURRENT_USER");
		if (user == null) {
			return "login";
		} else {
			modelMap.put("CURRENT_USER", JsonUtil.toJson(user));
			return "index";
		}
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(HttpSession session, String username, String password) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
		UserVo user = userService.findUser(username, password);
		if (user != null) {
			session.setAttribute("CURRENT_USER", user);
            resultMap.put("logined", true);
		} else {
            resultMap.put("logined", false);
        }
		return resultMap;
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession session) {
		session.invalidate();
		return "login";
	}
}
